package com.tiancikeji.zaoke.gui.http;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;

public class FileLoader extends DefaultLoader{
	
	public String updateOrders(Map<Long, Long> orderIds, long zoneId) throws Throwable {
		StringBuilder sb = new StringBuilder();
		
		if(orderIds != null && orderIds.size() > 0){
			try{
				FileWriter fw = new FileWriter(new File(getUploadFileName(zoneId)), true);
				for(Long orderId : orderIds.keySet()){
					fw.append(orderId + "\t" + orderIds.get(orderId));
					fw.append("\n");
				}
				fw.flush();
				fw.close();
				sb.append("{\"status\":200}");
			} catch(Throwable t){
				t.printStackTrace();
				sb.append("{\"status\":400,\"msg\":\"" + StringUtils.join(orderIds.keySet(), "|") + "\"}");
			}
		}
		
		return sb.toString();
	}

	private String getUploadFileName(long zoneId) {
		return uploadURL + zoneId + "." + new SimpleDateFormat("yyyyMMdd").format(new Date());
	}

	@Override
	public String getOrders(long zoneId) throws Throwable {
		StringBuilder sb = new StringBuilder();
		Scanner sc = new Scanner(new File(downloadURL + zoneId + "." + new SimpleDateFormat("yyyyMMdd").format(new Date())));
		while(sc.hasNextLine())
			sb.append(sc.nextLine());
		sc.close();
		return sb.toString();
	}

	@Override
	public Map<Long, String> getTokenOrders(long zoneId) {
		Map<Long, String> result = new HashMap<Long, String>();
		Scanner sc;
		try {
			File file = new File(getUploadFileName(zoneId));
			if(file.exists() && file.canRead()){
				sc = new Scanner(file);
				while(sc.hasNextLine()){
					String line = sc.nextLine();
					String[] lines = StringUtils.split(line, "\t");
					if(lines.length > 1)
						result.put(NumberUtils.toLong(lines[0]), new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(NumberUtils.toLong(lines[1]))));
					else if(lines.length == 1)
						result.put(NumberUtils.toLong(lines[0]), new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
				}
				sc.close();
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		return result;
	}
}
